package com.hk.interceptor;

import com.hk.constants.ConstantsUtil;
import com.hk.utils.TraceIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: dpb
 * @Description 添加TraceId拦截器
 * @date: 2023/1/6 13:53
 * @Version 1.0
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(ConstantsUtil.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = TraceIdUtil.generateTraceId();
        }
        MDC.put(ConstantsUtil.TRACE_ID, traceId);
        //将当前产生一次完整的请求的traceId放到响应头，前端可以看到
        response.setHeader(ConstantsUtil.TRACE_ID, traceId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //调用结束后要删除，避免内存泄露
        MDC.remove(ConstantsUtil.TRACE_ID);
    }
}
